Passed
Pull Request — dev (#7)
by Oscar
03:03
created

Map.tsx ➔ Map   C

Complexity

Conditions 6

Size

Total Lines 159
Code Lines 107

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 107
dl 0
loc 159
rs 6.0666
c 0
b 0
f 0
cc 6

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
import { useState, useEffect } from 'react';
2
import { ScrollView, Image, Text, View, StyleSheet, StatusBar, Button, Pressable } from 'react-native';
3
import MapView, { Marker, Circle, Polygon } from 'react-native-maps';
4
import * as Location from 'expo-location';
5
import React from 'react';
6
import mapModel from '../models/map';
7
import scooterModel from '../models/scooter';
8
import {API_KEY} from "@env";
9
import config from '../config/config.json';
10
import Icon from 'react-native-vector-icons/Octicons';
11
import ScooterModal from './ScooterModal';
12
import NavBar from './drawer/NavBar';
13
import ZoneModal from './ZoneModal';
14
15
export default function Map({navigation, API_KEY, position, setPosition, token}): any {
16
    const [locationMarker, setLocationMarker] = useState(null);
17
    const [highlight, setHighlight] = useState(null);    
18
    const [currentCity, setCurrentCity] = useState(null);
19
    const [zones, setZones] = useState([]);
20
    const [scooters, setScooters] = useState([]);
21
    const [currentScooter, setCurrentScooter] = useState(null);
22
    const [modalVisible, setModalVisible] = useState(false);
23
    const [zoneModalVisible, setZoneModalVisible] = useState(false);
24
    const [currentZone, setCurrentZone] = useState(null);
25
    
26
    
27
    /**
28
     * Set user position
29
     */
30
    useEffect(() => {
31
        async function fetchPosition(): Promise<void> {
32
            const { status } = await Location.requestForegroundPermissionsAsync();
33
34
            // if (status !== 'granted') {
35
            //     setErrorMessage('Permission to access location was denied');
36
            //     return;
37
            // }
38
39
            const currentLocation = await Location.getCurrentPositionAsync({});
40
41
            const userCoordinates = {
42
                //latlang hardcoded for testing
43
                // latitude: currentLocation.coords.latitude,
44
                // longitude: currentLocation.coords.longitude
45
                latitude: 56.161013580817986,
46
                longitude: 15.587742977884904
47
            };
48
49
    
50
            setPosition(userCoordinates);
51
            
52
            mapModel.getClosestCity(position);
53
54
            setLocationMarker(<Marker
55
                coordinate={{
56
                    //latlang hardcoded for testing
57
                    // latitude: currentLocation.coords.latitude,
58
                    // longitude: currentLocation.coords.longitude
59
                    latitude: 56.161013580817986,
60
                    longitude: 15.587742977884904
61
                }}
62
                title="My location"
63
                pinColor="blue"
64
                flat={false}
65
            />);
66
        };
67
68
69
        fetchPosition();
70
71
    }, []);
72
73
    /**
74
     * Set city to city that is closest to user and zones for that city
75
     */
76
    useEffect(() => {
77
        async function setUpMap(): Promise<void> {
78
            const city = await mapModel.getClosestCity(position);
79
            
80
            
81
            // Set city that is closest to user
82
            setCurrentCity(city);
83
                        
84
            /**
85
             * Set zones on map
86
             */
87
            const zones = mapModel.getZones(city);
88
            setZones(zones);
89
90
91
            /**
92
             * Get all scooters and create markers for them on the map
93
             */
94
            const result = await scooterModel.getScooters(API_KEY, city); 
95
96
            const scooters = result['cityScooters'];
97
            const sortedScooters = scooterModel.sortAvailableScooters(scooters);
98
            // console.log(scooters[0]);
99
            
100
            // console.log(sortedScooters[0]);
101
102
            setScooters(sortedScooters);
103
            
104
        };
105
        setUpMap();
106
    }, []);
107
108
109
    function DrawerButton({navigation}) {
110
        return (
111
          <Pressable style={[styles.drawer, styles.shadowProp]} onPress={() => navigation.openDrawer()}> 
112
            <Icon 
113
            name='three-bars' 
114
            size={30} 
115
            color='black'
116
            />
117
          </Pressable>
118
        );
119
      };
120
121
    return (
122
        <View style={styles.container}>
123
            <MapView
124
                style={styles.map}
125
                region={{
126
                    latitude: position.latitude? position.latitude : 0,
127
                    longitude: position.longitude? position.longitude : 0,
128
                    latitudeDelta: 0.03,
129
                    longitudeDelta: 0.03,
130
                }}
131
                userInterfaceStyle={'dark'}
132
            >
133
                {locationMarker}
134
135
                {scooters.map((s, index) => 
136
                    <Marker
137
                        // title={s['name']}
138
                        // description={`Charge ${s['battery']}% ${s['status']}`}
139
                        coordinate={s['coordinates']}
140
                        icon={require('../assets/Scooter1.png')}
141
                        tappable={true}
142
                        key={index}
143
                        onPress={() => {
144
                            setCurrentScooter(s)
145
                            setModalVisible(true)
146
                        }}
147
                        >
148
                    </Marker>
149
                )}
150
                {zones.map((z, index) => (                    
151
                    <Polygon 
152
                        coordinates={z['coordinates']}
153
                        strokeColor={z['zoneColor']}
154
                        strokeWidth={3}
155
                        fillColor={z['zoneColor']}
156
                        key={index}
157
                        tappable={true}
158
                        onPress={() => {
159
                            setCurrentZone(z)
160
                            setZoneModalVisible(true)                            
161
                        }}
162
                    />
163
                ))}
164
            </MapView>
165
166
    
167
            <ScooterModal navigation={navigation} scooter={currentScooter} modalVisible={modalVisible} currentCity={currentCity} setModalVisible={setModalVisible} />
168
169
            <ZoneModal navigation={navigation} zone={currentZone} zoneModalVisible={zoneModalVisible} setZoneModalVisible={setZoneModalVisible} />
170
171
            <NavBar navigation={navigation} />
172
        </View>
173
    )
174
}
175
176
const styles = StyleSheet.create({
177
    container: {
178
        // flex: 1,
179
        height: '100%',
180
        alignItems: "center",
181
        width: '100%'
182
    },
183
184
    map: {
185
        position: 'absolute',
186
        top: 0,
187
        left: 0,
188
        bottom: 0,
189
        right: 0,
190
    },
191
192
    drawer: {
193
        position: 'absolute',
194
        width: 50,
195
        height: 50, 
196
        left: 50,
197
        backgroundColor: 'white',
198
        marginTop: 50,
199
        borderRadius: 25,
200
        justifyContent: 'center',
201
        alignItems: 'center'
202
    },
203
    
204
    shadowProp: {
205
        elevation: 5,
206
        shadowColor: 'black'
207
      },
208
});
209
210